from PySide2.QtCharts import QtCharts
from PySide2.QtCore import Qt


def data_list_to_series(series: QtCharts.QLineSeries, data_list):
    x_value = 0
    points_vector = series.pointsVector()
    if points_vector:
        last_point = points_vector.at(points_vector.size() - 1)
        x_value = last_point.x()
    x_new_value = x_value + 1
    for data in data_list:
        series.append(x_new_value, data)
        x_new_value += 1


def append_data_list_to_series(series: QtCharts.QLineSeries, data_list):
    index = series.count() + 1
    for data in data_list:
        series.append(index, data)
        index += 1


class Line_Chart:
    def __init__(self, title, y_name, y_max, y_min):
        self.chart = QtCharts.QChart()
        self.chart.setTitle(title)

        self.xAxis = QtCharts.QValueAxis()
        self.xAxis.setTitleText('数据数量')
        self.x_step = 5
        self.x_point_count = 60
        self.xAxis.setTickCount(self.x_point_count)
        self.chart.addAxis(self.xAxis, Qt.AlignBottom)

        self.yAxis = QtCharts.QValueAxis()
        self.yAxis.setTitleText(y_name)
        self.chart.addAxis(self.yAxis, Qt.AlignLeft)

        self.x_max = 100
        self.set_x_range()
        self.yAxis.setRange(y_min, y_max)
        self.series_dict = {}
        self.axis_x = QtCharts.QValueAxis()
        self.axis_x.setLabelFormat('%.1f')
        self.axis_x.setTitleText('X')
        self.axis_x.setTickCount(11)
        self.axis_x.setMinorTickCount(4)

    def add_series(self, series_name_list, ):
        for series_name in series_name_list:
            series = QtCharts.QLineSeries()
            series.setName(series_name[1])
            self.series_dict[series_name[0]] = series
            series.attachAxis(self.xAxis)
            series.attachAxis(self.yAxis)
            self.chart.addSeries(series)

    def set_x_range(self):
        self.x_max = self.x_step * self.x_point_count * 2
        self.xAxis.setRange(0, self.x_max)

    def append_data(self, data_list):
        max_x = 0
        for data_dict in data_list:
            data_name = data_dict["name"]
            data = data_dict["data"]
            series = self.series_dict[data_name]
            append_data_list_to_series(series, data)
            max_x = max(max_x, len(data))
        if max_x / self.x_max > 0.8:
            self.x_step = int((max_x + 2) / (self.x_point_count - 1))
            self.set_x_range()
